"""
线程同步-Semaphore使用以及源码分析

核心知识点：
    1.Semaphore是用于控制进入数量的锁。
    2.文件读写，写一般只是用于一个线程写，读可以允许有多个。

应用场景：
    1.爬虫
"""

import time
import threading
from threading import Semaphore


class HtmlSpider(threading.Thread):
    def __init__(self, url, sem):
        self.url = url
        self.sem = sem
        super().__init__()

    def run(self):
        time.sleep(2)
        print("got html text success")
        self.sem.release()


class UrlProducer(threading.Thread):
    def __init__(self, sem):
        self.sem = sem
        super().__init__()

    def run(self):
        for i in range(10):
            self.sem.acquire()
            html_thread = HtmlSpider("http://projectsedu.com/{id}".format(id=i), sem=self.sem)
            html_thread.start()


def use_thread():
    # 一次只允许3个并发
    sem = Semaphore(3)
    url_producer = UrlProducer(sem=sem)
    url_producer.start()
    # 输出结果：
    """
    got html text success
    got html text success
    got html text success
    got html text success
    got html text success
    got html text success
    got html text success
    got html text success
    got html text success
    got html text success
    """


if __name__ == '__main__':
    use_thread()
